﻿using DevExpress.Blazor;
using DevExpress.CodeParser;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Blazor.Components.Models;
using DevExpress.ExpressApp.Blazor.Editors;
using DevExpress.ExpressApp.Core;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.Security;
using HC.XAP.FileSystemData.BusinessObjects;
using HC.XAP.FileUpload.Module.BusinessObjects.FileUpload;
using Microsoft.AspNetCore.Components;


namespace HC.XAP.FileUpload.Blazor.Server.Editors.DxBatchUpload
{
    public class DxBatchUploadEditor : BlazorPropertyEditorBase
    {
        
        public DxBatchUploadEditor(Type objectType, IModelMemberViewItem model) : base(objectType, model)
        {
            
        }
        public override DxBatchUploadModel ComponentModel =>(DxBatchUploadModel) base.ComponentModel;

        protected override IComponentModel CreateComponentModel()
        {
            var model = new DxBatchUploadModel();
            model.AllowMultiFileUpload = true;
            //model.UploadMode = DevExpress.Blazor.UploadMode.OnButtonClick;
            model.AllowCancel = false;
            model.SelectButtonText = "选择文件...";
            //model.MaxFileCount = 5;
            model.FilesUploading = EventCallback.Factory.Create<FilesUploadingEventArgs>(this, async value =>
            {
               await OnFilesUploading(value);
            });

            model.SelectedFilesChanged = EventCallback.Factory.Create<IEnumerable<UploadFileInfo>>(this, value =>
            {
                SelectedFilesChanged(value);
            });

            return model;
        }

        async Task OnFilesUploading(FilesUploadingEventArgs args)
        {
           
            var upParameter = this.View.CurrentObject as UploadFileParameters;
            foreach (IFileInputSelectedFile upFile in args.Files)
            {
                using var stream = new MemoryStream();
                await upFile.OpenReadStream(upFile.Size).CopyToAsync(stream);
                var f = new DxUploadFileInfo(upFile.Name,upFile.Size, stream);
                upParameter.FileStreams.Add(f);
            }
        }

        protected void SelectedFilesChanged(IEnumerable<UploadFileInfo> files)
        {
            var upParameter = this.View.CurrentObject as UploadFileParameters;
            foreach(var f  in upParameter.FileStreams.ToList())
            {
                if(!files.Any(a=>a.Name==f.FileName))
                {
                    upParameter.FileStreams.Remove(f);
                }
            }
        }

        protected override void ReadValueCore()
        {
            base.ReadValueCore();
        }
        protected override void WriteValueCore()
        {
            base.WriteValueCore();
            
        }
        protected override object GetControlValueCore()
        {
           return base.GetControlValueCore();
        }
    }
}
